<template>
  <div>
    <!-- 头部 -->
    <a-form ref="searchRef" :model="searchForm" style="margin-bottom: 20px">
      <a-row>
        <a-form-item label="编号" name="ticketName">
          <a-input
            placeholder="请输入"
            v-model:value="searchForm.number"
            allow-clear
          ></a-input>
        </a-form-item>
        <a-form-item label="优惠名称">
          <a-input
            placeholder="请输入"
            v-model:value="searchForm.ticketName"
            allow-clear
          ></a-input>
        </a-form-item>
        <a-form-item name="saleValue" label="参与人群">
          <a-select
            ref="select"
            v-model:value="searchForm.joinCrowd"
            @focus="focus"
            @change="handleChange"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in isAttestStatusList"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item name="saleValue" label="发放形式">
          <a-select
            ref="select"
            v-model:value="searchForm.grantShape"
            @focus="focus"
            @change="handleChange"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in fangType"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="使用条件">
            <a-select
              ref="select"
              v-model:value="searchForm.useTypeId"
              @focus="focus"
              @change="handleChange"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in options3"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item name="saleValue" label="状态：">
            <a-select
              ref="select"
              v-model:value="searchForm.ticketStatus"
              @focus="focus"
              @change="handleChange"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in buyCar1"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center"
            >搜索</a-button
          >
        </a-col>
        <a-col :span="2">
          <a-button @click="reset" class="d-a-center">重置</a-button>
        </a-col>
      </a-row>
    </a-form>

    <!-- 列表 -->
    <a-table
      :columns="columns"
      :data-source="list"
      bordered
      key="id"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <!-- :row-selection="rowSelection" -->
      <!-- -->

      <template #joinCrowd="{ record }">
        <div>{{ isAttestStatusList1[record.joinCrowd] }}</div>
      </template>
      <template #grantShape="{ record }">
        <div>{{ fangType2[record.grantShape] }}</div>
      </template>
      <template #useTypeId="{ record }">
        <div>{{ options2[record.useTypeId] }}</div>
      </template>
      <template #faceValueSum="{ record }">
        <div>
          {{
            money1[record.faceValueId] +
            record.faceValueSum +
            (record.faceValueId == 1 ? "元" : "折")
          }}
        </div>
      </template>
      <!-- <template #stack="{ record, index }">
        <div @click="changeStack(record.status, index, record.id)">
          <a-switch
            v-model:checked="record.status"
            :checkedValue="0"
            :unCheckedValue="1"
          />
        </div>
      </template> -->
      <template #operation="{ record }">
        <a-button
          type="link"
          @click="handleDetail(record)"
          v-has="{ a: $route, b: 1 }"
          >查看</a-button
        >
        <a-button
          type="link"
          @click="handleDetail(record, 2)"
          v-if="record.ticketStatusName == '待审核'"
          v-has="{ a: $route, b: 2 }"
          >审核</a-button
        >
        <!--  -->
      </template>
    </a-table>
    <!-- 多项删除 -->
    <!-- <a-button type="danger" @click="listDel">删除</a-button> -->
  </div>
</template>
<script>
import {
  reactive,
  ref,
  computed,
  createVNode,
  watch,
  toRefs,
  unref,
  toRaw,
  isReactive,
  toRef,
} from "vue";
import router from "@/router/index.js";
import {
  isAttestStatusList,
  useOptions1,
  options3,
  fangType,
  money,
  isRealNameList,
  ports,
  swiperType,
  isAttestStatusList1,
  serviceOptions,
  useOptions,
  options2,
  fangType2,
  money1,
  buyCar1,
} from "@/utils/dict.js";
import {
  CheckOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { uploadPicture } from "@/api/service/index.js";
import { Modal, message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import * as api from "@/api/market/index.js"; // } // deleteConsumableBag, // updateAndAddConsumableBag, // selectAllDetail, // upOrDownConsumableBag, // selectAllConsumableBag, // {
import { selectAllService, selectAllType } from "@/api/service/index.js";
import { deleteObjBlank } from "@/assets/js/common.js";
import { useModal } from "@/hooks"

export default {
  setup() {
    const searchRef = ref("");
    const formRef = ref("");

    const data = reactive({
      list: [],
      loading: true,
      visible: false,
      serviceList: [], //分类列表
      detaiList: [],
      consumables: [], //默认绑定ID即可
      statusAct: 0,
      searchForm: {},
      typeList: [],
      form: { isDele: 0, money: 1 },
      value: [], //分类-这个远程加载的数据好像不可以哎
      defaultValue: [],
      detailImage: [],
      ports,
      swiperType: true ? [...swiperType.splice(0, 1)] : [...swiperType],
      isAttestStatusList1,
      isAttestStatusList,
      buyCar1,

      options3,
      serviceOptions,
      useOptions,
      options2,
      fangType2,
      fangType,
      money1,
    });

    const title = ref(""); //分类名称

    const modalTitle = ref("新增耗材");
    const rules = {
      //  portValue: [{ required: true, message: '请选择端口!', trigger: 'change'}],
      //  inputValue: [{ required: true, message: '请输入搜索内容!', trigger: 'blur'}],
    };
    const rules1 = {
      name: [{ required: true, message: "请输入耗材名称!" }],
      sellPrice: [{ required: true, message: "请输入销售价!" }],
      serviceId: [{ required: true, message: "请输入服务类型!" }],
      typeId: [{ required: true, message: "请输入服务分类!" }],
      bazaarPrice: [{ required: true, message: "请输入市场价格!" }],
      cc: [
        { required: true, message: "请输入" },
        {
          pattern: /([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/,
          // /^\+?[1-9]\d*$/,
          message: "大于0的正整数",
          trigger: ["change", "blur"],
        },
      ],
      // ([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])
      // 大于0的数据

      // value: [{ required: true, message: "请选择耗材分类!" }],
    };

    // 分页器
    const page = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0,
    });

    const saleStatusOptions = reactive([
      {
        name: "全部",
        id: "",
      },
      {
        name: "上架",
        id: 0,
      },
      {
        name: "下架",
        id: 1,
      },
    ]);
    const consumeOptions = reactive([
      {
        name: "耗材名称",
        id: 1,
      },
      {
        name: "耗材分类",
        id: 1,
      },
    ]);
    const delListId = ref([]); //删除数组ID集合
    const chooseStatus = (status, index) => {
      data.statusAct = index;
      data.searchForm.status = status;
      page.pageNum = 1;
      init();
    };
    // 查询
    const search = () => {
      page.current = 1;
      init();
    };
    const columns = [
      {
        title: "id",
        dataIndex: "id",
        className: "table",
      },
      {
        title: "编号",
        dataIndex: "ticketNumber",
        className: "table",
      },
      {
        title: "优惠名称",
        dataIndex: "ticketName",
        className: "table",
      },
      {
        title: "参与人群",
        dataIndex: "joinCrowd",
        className: "table",
        slots: {
          customRender: "joinCrowd",
        },
      },
      {
        title: "发放形式",
        dataIndex: "grantShape",
        className: "table",
        slots: {
          customRender: "grantShape",
        },
      },
      {
        title: "使用条件",
        dataIndex: "useTypeId",
        className: "table",
        slots: {
          customRender: "useTypeId",
        },
      },
      {
        title: "面值",
        dataIndex: "faceValueSum",
        className: "table",
        slots: {
          customRender: "faceValueSum",
        },
      },
      {
        title: "创建时间",
        dataIndex: "createdTime",
        className: "table",
      },
      {
        title: "状态",
        dataIndex: "ticketStatusName",
        className: "table",
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        slots: {
          customRender: "operation",
        },
      },
    ];

    // 分页器
    const pagination = computed(() => ({
      current: page.pageNum,
      pageSize: page.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      page.pageNum = pagination.current;
      page.pageSize = pagination.pageSize;

      // 请求列表接口
      init();
    };
    const cancel = () => {
      data.visible = false;
      title.value = "";
      data.form = {};
      data.consumables = [];
    };
    // 新增
    const add = () => {
      // data.visible = true;
      router.push({
        path: "/market/detail/detail",
      });
    };
    // 查看
    const handleDetail = (item, type = 1) => {
      // data.visible = true;
      router.push({
        path: "/market/detail/detail",
        query: { item: JSON.stringify(item), type: type },
      });
    };
    const handleUpdateBefore = async (item, name = 1, tip) => {
      // 1：启用 2：关闭 3：结束
      const {closeModal} = useModal.confirm({
        content: () => "你确定要" + tip,
        onOk: async () => {
          handleUpdate(item, name);
          closeModal()
        },
      });
    };
    const handleUpdate = async (item, name = 1) => {
      // 1：启用 2：关闭 3：结束
      let res = await api.operationStatus({ id: item.id, ticketStatus: name });
      if (res.success) {
        message.success("操作成功");
        page.pageNum = 1;
        init();
      }
    };
    const handleEdit = async (item, name = "编辑") => {
      router.push({
        path: "/market/detail/detail",
        id: item.id,
      });
      // item.typeId = String(item.typeId);
      // console.log(item, "item");
      // data.form = item;
      // data.consumables = item.consumables.map((el) => el.id);
      // modalTitle.value = name;
      // data.value[0] = String(item.typeId);
      // data.visible = true;

      // 二级分类
      // let obj = item;
      // item.id = obj.typeId;
      // loadData([item]);
      // let obj = {
      //   pageNum: 1,
      //   pageSize: 80,
      //   typeId: item.typeId,
      // };
      // let res = await selectAllService(obj);
      // if (res.success) {
      //   let index = data.typeList.findIndex((el) => el.id == item.typeId);
      //   console.log(index, "查找到的index是-----");
      //   res.object.records.map((el) => (el.name = el.serveName));
      //   data.typeList[index].children = res.object.records;

      //   data.typeList = [...data.typeList];
      // }
      // data.value[1] = item.serviceId;

      // console.log(data.value, "默认选中的是");
    };
    const Typename = (id) => {
      let item = data.typeList.find((el) => el.id == id);
      console.log(item, "分类名字是");
      return item;
    };

    const serviceName = (id) => {
      let list = data.serviceList.find((el) => el.id == id);
      if (list.serviceName) {
        // return list.serveName;

        return list;
      }
    };

    const closeModal = (e) => {
      data[e] = false;
      if (e == "itemVisible") {
        data.itemForm = {};
      }
      if (e == "visible") {
        data.form = {};
        data.packageList = [];
        data.itemList = [];
      }
    };
    // 删除
    const handleDel = (key, name) => {
      const {closeModal} = useModal.confirm({
        title: () => "你确定删除+ " + name + "+吗?",

        onOk: async () => {
          let res = await api.deleteItem({ id: key });
          if (res.success) {
            message.success("删除成功");
            init();
            closeModal()
          }
        },

        class: "test",
      });
    };
    const selectConsume = (e) => {
      console.log(e);
    };
    const selectService = (e) => {
      // console.log(e, "服务类型");s
    };
    const selectType = (e) => {};
    // 上传头图
    const uploadDetail_image = (file) => {
      uploadImage(file, "detailImage");
    };
    // 公共的上传图片
    const uploadImage = async (file, e) => {
      let formData = new FormData();
      formData.append("file", file.file);
      let res = await uploadPicture(formData, "ali");
      // // url存入列表中,为什么是两个fileList
      data[e] = data[e].filter((el) => el.status == "done");
      if (res.success) {
        data[e].push({
          uid: file.file.uid,
          url: res.object,
          status: "done",
          name: file.file.name,
        });
      }
      console.log(data[e], "data[e]是--");
    };
    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          "selectedRows: ",
          selectedRows
        );
        delListId.value = selectedRowKeys;
      },
      onSelect: (record, selected, selectedRows) => {
        //console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        //console.log(selected, selectedRows, changeRows,'全选操作');
        // 数组项
      },
    });

    // 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
    const changeStack = (checked, index, id) => {
      console.log(page.pageNum);
      console.log(checked, index, "是否上下架");
      let title = checked == 0 ? "上架" : "下架";
      // 弹框提示？确定上下架吗
      const {closeModal} = useModal.confirm({
        title: () => `确定${title}当前耗材包吗?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await upOrDownConsumableBag(id);
          if (res.success) {
            data.list[index].status = Number(checked);
            closeModal()
          }
        },
        onCancel() {
          let flag = checked == 0 ? 1 : 0;
          data.list[index].status = flag;
          closeModal()
        },
        class: "test",
      });
    };
    initServiceList();

    init();
    // initAllDetailList();
    async function init() {
      if (data.searchForm.status == 0) {
        delete data.searchForm.status;
      }
      let obj = {
        pageNum: page.pageNum,
        pageSize: page.pageSize,
        ...data.searchForm,
      };
      let res = await api.ticketAuditList(obj);
      if (res.success) {
        res.object.list.map((el) => (el.key = el.id));
        // debugger
        // console.log(data.options2,'options2options2options2')
        // let arr = res.object.list.map(m => {
        //   return {
        //     ...m,
        //     grantShape: m.grantShape
        //     // grantShape: data.fangType[m.grantShape].name,
        //     // useTypeId: options2[m.useTypeId].name
        //   }

        // })
        // console.log(arr,'\\\\\\\\')
        data.list = [...res.object.list];
        // data.list.forEach(el=>{
        // })
        data.loading = false;
        page.total = res.object.total;
      }
    }
    // 一级分类
    async function initServiceList() {
      let obj = {
        pageNum: 1,
        pageSize: 80,
      };
      let res1 = await selectAllType(obj);
      if (res1.success) {
        res1.object.records.map((el) => (el.isLeaf = false)); //id是string类型的
        data.typeList = res1.object.records;
      }
    }
    // async function initAllDetailList() {
    //   let res = await selectAllDetail();
    //   if (res.success) {
    //     data.detaiList = res.object;
    //   }
    // }

    const loadData = async (selectedOptions) => {
      console.log("点击了选择", selectedOptions);
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily

      let obj = {
        pageNum: 1,
        pageSize: 80,
        typeId: selectedOptions[0].id,
      };
      let res = await selectAllService(obj);
      if (res.success) {
        targetOption.loading = false;
        res.object.records.map((el) => (el.name = el.serveName));
        targetOption.children = res.object.records;

        data.typeList = [...data.typeList];
      }
    };
    const methods = {
      reset() {
        data.searchForm = {};
        page.page = 1;
        init();
      },
    };
    return {
      ...toRefs(data),
      ...methods,
      saleStatusOptions,
      consumeOptions,
      searchRef,
      modalTitle,
      formRef,
      rules,
      rules1,
      columns,
      pagination,
      title,
      labelCol: { style: { width: "250px" } },
      labelCol1: { style: { width: "150px" } },
      wrapperCol: { span: 20 },
      handleTableChange,
      search,
      add,
      handleDel,
      handleUpdateBefore,
      cancel,
      handleEdit,
      rowSelection,
      changeStack,
      serviceName,
      selectConsume,
      selectService,
      chooseStatus,
      Typename,
      selectType,
      loadData,
      uploadDetail_image,
      closeModal,
      handleUpdate,
      handleDetail,
    };
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
    PlusOutlined,
  },
};
</script>

<style scoped lang="less">
.act {
  color: #2a9d8f;
}
</style>
